package cn.ynrcb.personnelfile.aspect;

import cn.ynrcb.personnelfile.admin.dao.BusinessLogDao;
import cn.ynrcb.personnelfile.admin.entity.BusinessLogEntity;
import cn.ynrcb.personnelfile.common.annotation.BusinessLog;
import cn.ynrcb.personnelfile.common.utils.HttpContextUtils;
import cn.ynrcb.personnelfile.common.utils.IPUtils;
import cn.ynrcb.personnelfile.common.utils.Request2MapUtil;
import cn.ynrcb.personnelfile.sysadmin.entity.SysUserEntity;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 业务日志 - 切面
 * @作者: swg
 * @时间： 2021-12-2 11:41:37
 **/
@Aspect
@Component
public class BusinessLogAspect {
    // 使用指定BusinessLogAspect初始化日志对象，方便打印日志
    private static Logger logger = LoggerFactory.getLogger(BusinessLogAspect.class);

    @Autowired
    private BusinessLogDao businessLogDao;

    // 切点为自定义注解
    @Pointcut("@annotation(cn.ynrcb.personnelfile.common.annotation.BusinessLog)")
    public void logPointCut() {

    }

    // 设置环绕通知
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行目标方法
        Object result = point.proceed();
//		logger.info("切面日志结果：{}", result.toString());
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveLog(point, time);

        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        BusinessLogEntity log = new BusinessLogEntity();
        BusinessLog businessLog = method.getAnnotation(BusinessLog.class);
        String reqName = businessLog.value(); // 获取注解的值（参数）
        log.setType(reqName);
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.setMethod(className + "." + methodName + "()"); // 拼接调用的方法（类名+方法名）

        //请求的参数
        Object[] args = joinPoint.getArgs(); // 获取目标方法的请求参数
        try{
            String params = new Gson().toJson(args); // 将java对象转换为json字符串
            log.setParams(params);
        }catch (Exception e){

        }
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        
        log.setResCode(""); //返回状态码
        //设置IP地址
        log.setIp(IPUtils.getIpAddr(request));

        if(null != SecurityUtils.getSubject().getPrincipal()) {
            String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
            log.setOperateUser(username);
        }else {
            log.setOperateUser("");
        }
        Map<String, Object> reqParams = Request2MapUtil.getParameterMap(request);
        if(null == log.getParams() && null != reqParams){
            log.setParams(JSON.toJSONString(reqParams));
        }

        log.setTime(time);
        businessLogDao.insert(log);
    }


}
